package com.nd.mobile.study.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.RemoteViews;

import com.nd.mobile.study.R;
import com.nd.mobile.study.common.constants.BundleConstants;

public class AppInstallService extends Service {
	private static final String	FILE_NAME_SEPARATOR	= ".";
	
	private static boolean sIsDownloading;

	private String				TAG					= this.getClass().getName();

	boolean						endFlag;											// 结束标记

	private String				fileDirectory		= "";

	private String				strURL				= "";

	private String				fileExt				= "";

	private String				fileName			= "";

	private String				fileURL				= "";

	int							value;

	private RemoteViews			contentView;

	private Notification		mNotification		= new Notification();

	private NotificationManager	mNotificationMgr;

	private Intent				mIntent;

	private PendingIntent		mPendingIntent;									// 更新显示

	public static boolean isDownloading() {
		return sIsDownloading;
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		android.os.Debug.waitForDebugger();
		mNotificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		contentView = new RemoteViews(getPackageName(), R.layout.download);

		// 通知的图标必须设置(其他属性为可选设置),否则通知无法显示
		mNotification.icon = R.drawable.ico_hxjy;
		contentView.setImageViewResource(R.id.image, R.drawable.ico_hxjy);// 起一个线程用来更新progress
		endFlag = false;
		// 获取欲安装程序的文件名，apk地址为更新配置文件中versionUrl的路径，如果为空则用Config.APP_URL
		String apkPath = intent.getStringExtra(BundleConstants.VITAMIO_APK_URL);
//		strURL = (StringUtils.isBlank(apkPath)) ? Config.Update.LATEST_VERSION_APK : apkPath;
		strURL = apkPath;
		fileExt = strURL.substring(strURL.lastIndexOf(FILE_NAME_SEPARATOR) + 1, strURL.length()).toLowerCase();
		fileName = strURL.substring(strURL.lastIndexOf(File.separator) + 1, strURL.lastIndexOf(FILE_NAME_SEPARATOR));
		fileDirectory = getSdCardPath();
		fileURL = fileDirectory + File.separator + fileName + FILE_NAME_SEPARATOR + fileExt;
		createFile();
		if (checkSDCard()) {
			// 起新线程去下载文件
			new Thread() {
				@Override
				public void run() {
					while (!endFlag) {
						try {
							getDataSource(strURL);
						} catch (Exception e) {
							Log.e(TAG + " getDataSource:", e.getMessage());
						}
					}
				}
			}.start();
		}

	}

	/**
	 * 得到SD卡路径
	 * 
	 * @return
	 */
	public String getSdCardPath() {
		File sdCardDir = Environment.getExternalStorageDirectory();
		String path = sdCardDir.getParent() + File.separator + sdCardDir.getName();
		return path + java.io.File.separator + "Download";
	}

	/**
	 * 创建文件夹
	 */
	public void createFile() {
		try {
			if (checkSDCard()) {
				File path = new File(fileDirectory);
				if (!path.exists()) {
					path.mkdir();
				}
			}
		} catch (Exception e) {
			Log.e(TAG + " createFile:", e.getStackTrace().toString());
		}
	}

	/**
	 * 判断是否存在sd卡
	 * 
	 * @return
	 */
	private boolean checkSDCard() {
		return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	}

	private void getDataSource(String strPath) throws Exception {
		if (!URLUtil.isNetworkUrl(strPath)) {
			Log.w(TAG, "URL error");
		} else {
			// 获得提示的Intent
			mIntent = new Intent(Intent.ACTION_VIEW);
			mIntent.addCategory(Intent.CATEGORY_DEFAULT);
			mIntent.setComponent(new ComponentName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity"));
			mIntent.setDataAndType(Uri.fromFile(new File(fileURL)), "application/vnd.android.package-archive");
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mPendingIntent = PendingIntent.getActivity(this, 0, mIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
			// 取得URL
			URL mURL = new URL(strPath);
			// 创建链接
			URLConnection conn = mURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			int totalSize = conn.getContentLength();
			if (is == null) {
				throw new RuntimeException("Stream is NULL");
			}
			Log.i("version3", fileDirectory + fileName + FILE_NAME_SEPARATOR + fileExt);
			// 创建文件
			File mFile = new File(fileDirectory, fileName + FILE_NAME_SEPARATOR + fileExt);
			FileOutputStream fos = new FileOutputStream(mFile);
			// String currentTempFilePath = mFile.getAbsolutePath();
			int size = 0;
			Double percent;
			byte buf[] = new byte[1024];
			long lastTime = System.currentTimeMillis();
			do {
				int numread = is.read(buf);
				Message msg = Message.obtain();
				Bundle data = new Bundle();
				if (numread <= 0) {
					endFlag = true;
					data.putInt("Percent", 100);
					msg.setData(data);
					mainHandler.sendMessage(msg);
					break;
				}
				size += numread;
				fos.write(buf, 0, numread);
				percent = new Double(Double.parseDouble(String.valueOf(size)) / Double.parseDouble(String.valueOf(totalSize))) * 100;

				if (lastTime + 1000 < System.currentTimeMillis()) {
					lastTime = System.currentTimeMillis();
					data.putInt("Percent", (int) Math.floor(percent));
					msg.setData(data);
					mainHandler.sendMessage(msg);
				}

			} while (true);

			try {
				fos.close();
				is.close();
			} catch (Exception ex) {
				Log.e(TAG, "error: " + ex.getMessage(), ex);
			}
		}
		if (endFlag) {
			this.stopSelf();
		}
	}

	private void showNotification(double percent) {

		value = (int) Math.floor(percent);
		contentView.setProgressBar(R.id.pb, 100, value, false);
		contentView.setTextViewText(R.id.tv, value + "%");// 关键部分，如果你不重新更新通知，进度条是不会更新的
		if (value == 0) {
			contentView.setTextViewText(R.id.text, "开始下载");
		} else if (value != 100) {
			sIsDownloading = true;
			contentView.setTextViewText(R.id.text, "正在下载...");
		} else if (value == 100) {
			sIsDownloading = false;
			contentView.setTextViewText(R.id.text, "下载完成，请点击安装");
			autoInstall();
		}
		mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		mNotification.contentView = contentView;
		mNotification.contentIntent = mPendingIntent;
		mNotificationMgr.notify(0, mNotification);
	}

	private void autoInstall() {
		File file = new File(fileURL);
		String type = "application/vnd.android.package-archive";

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), type);
		startActivity(intent);
	}

	private final Handler	mainHandler	= new Handler() {
											@Override
											public void handleMessage(Message msg) {
												Bundle data = msg.getData();
												int percent = data.getInt("Percent");
												showNotification(percent);
											}
										};

}
